import {Component, OnInit} from '@angular/core';
import {DatePipe} from '@angular/common';
import {EmitService} from '../../../providers/emit.service';
import {HttpService} from '../../../providers/http.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import {FormBuilder, FormGroup} from '@angular/forms';


@Component({
  selector: 'app-sysdept',
  templateUrl: './sysdept.component.html',
  styleUrls: ['./sysdept.component.css'],

})
export class SysDeptComponent implements OnInit {

  autoHeight: number = 480;
  tab = {
    name: '部门管理',
    url: '/page/system/dept',
    closeIcon: true
  };

  loading = false;
  _cnd: any = {};
  _ngTree=[];
  mapOfExpandedData: { [key: string]: [] } = {};
  deptKey;

  constructor(public emitService: EmitService,
              private httpService: HttpService,
              private message: NzMessageService,
              private fb: FormBuilder,
              private datePipe: DatePipe) {
  }

  ngOnInit() {

    //初始化表单
    this.buildForm();

    // 通知父组件
    this.emitService.tabsEmit.emit(this.tab);

    // 列表查询
    this.search(true);

  }

  search(reset: boolean = false): void {
    if (reset) {
    }

    this._cnd.params = {};

    this.loading = true;
    this.httpService.post('system/dept/treeList', this._cnd,  (result)=> {
      this.loading = false;
      if (result.code !== 0) {
        this.message.error('操作失败：' + result.msg);
        return;
      }
      this._ngTree = result.data;
      this._ngTree.forEach(item => {
        this.mapOfExpandedData[item.key] = this.convertTreeToList(item);
      });

    },(errorResult)=>{
      this.loading = false;
      this.message.error(errorResult.msg);
    });
  }

  collapse(array, data, $event: boolean): void {
    if ($event === false) {
      if (data.children) {
        data.children.forEach(d => {
          const target = array.find(a => a.key === d.key)!;
          target.expanded = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root):[] {
    const stack= [];
    const array:[] = [];
    const hashMap = {};
    stack.push({ ...root, level: 0, expand: true });

    while (stack.length !== 0) {
      const node = stack.pop()!;
      this.visitNode(node, hashMap, array);
      if (node.children) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          stack.push({ ...node.children[i], level: node.level! + 1, expand: true, parent: node });
        }
      }
    }

    return array;
  }

  visitNode(node, hashMap: { [key: string]: boolean }, array): void {
    if (!hashMap[node.key]) {
      hashMap[node.key] = true;
      array.push(node);
    }
  }

  isEditBtn = false;
  ngTreeDisabled = false;
  radioChange(id){
    this.deptKey = id;
    this.isEditBtn = true;
  }

  // form crud
  modalWidth=800;
  modalTitle='部门信息';
  validateForm: FormGroup;
  isVisible = false;
  isOkLoading = false;

  buildForm(){
    this.validateForm = this.fb.group({
      parentId:[null,null],
      deptId:[null,null],
      deptName: [null ,null],
      orderNum: [null ,null],
      leader: [null ,null],
      phone: [null ,null],
      email: [null ,null],
      status: [null ,null],
    });
  }

  saveOrUpdate(): void {
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
      return;
    }
    this.isOkLoading = true;
    let url = 'system/dept/add';
    let deptId = this.validateForm.value.deptId;
    if (deptId && deptId > 0) {
      url = 'system/dept/edit';
    }

    this.httpService.post(url, this.validateForm.value,  (result)=> {
      this.isOkLoading = false;
      if (result.code !== 0) {
        this.message.error('操作失败：' + result.msg);
        return;
      }
      this.isVisible = false;
      this.message.success('操作成功');
      this.search();
    },(errorResult)=>{
      this.isOkLoading = false;
      this.isVisible = false;
      this.message.error(errorResult.msg);
    });
  }

  deleteOne(item){

    if(item.children && item.children.length>0){
      this.message.error('操作错误，请先删除子节点');
      return;
    }

    this.httpService.post('system/dept/delete', {ids:item.key},  (result)=> {
      if (result.code !== 0) {
        this.message.error('操作失败：' + result.msg);
        return;
      }
      this.message.success('删除成功');
      this.search();
    },(errorResult)=>{
      this.message.error(errorResult.msg);
    });
  }

  editInfo(id){
    this.httpService.post('system/dept/getById', {deptId:id},  (result)=> {
      if (result.code !== 0) {
        this.message.error('操作失败：' + result.msg);
        return;
      }
      this.openOrCloseModal(true);
      this.validateForm.patchValue(result.data);
      if(this.validateForm.value.parentId==0){
        this.ngTreeDisabled = true;
      }
    },(errorResult)=>{
      this.message.error(errorResult.msg);
    });
  }

  // 列表上面的编辑按钮
  editInfoTop(){
    let id =this.deptKey;
    this.editInfo(id);
  }

  addByParent(node){
   this.openOrCloseModal(true);
    this.validateForm.patchValue({
      parentId:node.key
    });
  }

  openOrCloseModal(isVisible): void {
    this.autoHeight = document.documentElement.clientHeight -250;
    this.ngTreeDisabled = false;
    this.isVisible = isVisible;
    this.isOkLoading = false;
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsPristine();
      this.validateForm.controls[key].updateValueAndValidity();
    }
  }


}
